<template>
  <el-dialog :title="title" :visible.sync="open" @close="close">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="系统名称:" prop="systemId">
        <el-select v-model="form.systemId" clearable placeholder="请选择系统名称" @change="systemIdChange">
          <el-option
            v-for="(item, index) in systemIdList"
            :key="index"
            :label="item.systemCode + ' / ' + item.systemName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接口类型" prop="manageType">
        <el-select v-model="form.manageType" placeholder="请选择接口类型" @change="systemIdChange">
          <el-option
            v-for="dict in dict.type.manage_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接口名称" prop="serviceId">
        <el-select v-model="form.serviceId" clearable placeholder="请选择接口名称" @change="interfaceData">
          <el-option
            v-for="(item, index) in serviceManagerList"
            :key="index"
            :label="item.serviceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="接口地址">
        <el-input v-model="interfaceAddress" disabled />
      </el-form-item>

      <el-form-item label="请求方式">
        <el-select v-model="interfaceType" disabled>
          <el-option value="1" label="GET" />
          <el-option value="2" label="POST" />
        </el-select>
      </el-form-item>

      <div
        v-for="(domain, index) in domains"
        :key="domain.key"
        style="display: flex;"
      >
        <el-form-item
          :label="'参数名' + (index+1)"
          prop="key_my"
        >
          <el-input v-model="domain.key_my" placeholder="参数名" />
        </el-form-item>
        <el-form-item
          :label="'参数值' + (index+1)"
          prop="value"
        >
          <el-input v-model="domain.value" placeholder="参数值" />
        </el-form-item>
        <el-form-item>
          <el-button @click.prevent="removeDomain(domain)">删除</el-button>
        </el-form-item>
      </div>

      <el-form-item>
        <el-button @click="addDomain">新增参数</el-button>
      </el-form-item>
      <!--      <el-form-item label="请求参数" prop="params">-->
      <!--        <el-input v-model.trim="form.params" type="textarea" maxlength="200" placeholder="请输入内容" show-word-limit class="limit" />-->
      <!--      </el-form-item>-->
      <el-form-item label="cron表达式" prop="cron">
        <el-input v-model.trim="form.cron" readonly placeholder="请输入cron表达式" maxlength="30" show-word-limit class="limit" />
        <el-button @click="addCron">生成表达式</el-button>

      </el-form-item>
      <el-form-item label="预警通知人" prop="alarmUsers">
        <el-select
          v-model="form.alarmUsers"
          multiple
          collapse-tags
          placeholder="请选择"
          collapse-tag
          filterable
          clearable
        >
          <el-option v-for="(item) in receiveUserList" :key="item.id" :value="item.id" :label="item.realName" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="form.taskStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="开启"
          active-value="1"
          inactive-text="停止"
          inactive-value="2"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model.trim="form.remarks" type="textarea" maxlength="200" placeholder="请输入内容" show-word-limit class="limit" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="testConnect">测试连接</el-button>
      <el-button @click="reset">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
    <dt-Vcrontab ref="vcrontabRef" v-model.trim="form.cron" />
  </el-dialog>
</template>
<script>
import { getSystemListApi, pageApi } from '@/api/serviceManage/requestPartyServiceManage'
import { listMonitorAlarmUser } from '@/api/contactAlarm'
import { addRes } from '@/utils/editAlarmUser'
import { addServiceMonitor, connectTest, updateServiceMonitor } from '@/api/serviceMonitor/ServiceMonitor'

export default {
  name: 'AddService',
  dicts: ['manage_type', 'monitorStatus'],
  data() {
    return {
      canClick: true,
      title: '',
      open: false,
      form: {},
      domains: [
        {
          key_my: null,
          value: null
        }
      ],
      rules: {
        manageType: { required: true, message: '请选择接口类型', trigger: 'change' },
        systemId: { required: true, message: '请选择系统名称', trigger: 'change' },
        serviceId: { required: true, message: '选择接口名称', trigger: 'change' },
        params: { required: true, message: '请输入请求参数', trigger: 'blur' },
        cron: { required: true, message: '请设置cron表达式', trigger: 'change' },
        alarmUsers: { required: true, message: '请选择预警联系人', trigger: 'blur' }
      },
      systemIdList: [],
      receiveUserList: [],
      serviceManagerList: [],
      interfaceAddress: '',
      interfaceType: ''

    }
  },
  created() {
    getSystemListApi().then(({ code, data }) => {
      if (code === '00000') this.systemIdList = data
    })
    listMonitorAlarmUser({ pageNo: 1, pageSize: -1 }).then(res => {
      if (res.code === '00000') this.receiveUserList = res.data.rows
    })
  },
  methods: {
    close() {
      this.open = false
      this.domains = [
        {
          key_my: null,
          value: null
        }
      ]
      this.interfaceAddress = ''
      this.interfaceType = ''
      this.reset()
    },
    interfaceData(val) {
      const data = this.serviceManagerList.find(item => item.id === val)
      this.interfaceAddress = data.interfaceAddress
      this.interfaceType = data.interfaceType
    },
    addDomain() {
      this.domains.push({
        value: ''
      })
    },
    removeDomain(item) {
      var index = this.domains.indexOf(item)
      if (index !== -1) {
        this.domains.splice(index, 1)
      }
    },
    // 系统名称change
    systemIdChange () {
      if (this.form.manageType != null && this.form.systemId != null) {
        if (this.form.serviceId) {
          this.form.serviceId = ''
          this.interfaceAddress = ''
          this.interfaceType = ''
        }
        pageApi({
          systemId: this.form.systemId,
          manageType: this.form.manageType,
          pageNo: 1,
          pageSize: -1
        }).then(({ data: response }) => {
          this.serviceManagerList = response.rows
        })
      }
    },
    reset() {
      this.form = {
        id: null,
        systemId: null,
        manageType: null,
        serviceId: null,
        params: null,
        cron: null,
        remarks: null,
        status: '0',
        statusUpTime: null,
        delFlag: null,
        createTime: null,
        createUser: null,
        updateTime: null,
        taskStatus: '2',
        updateUser: null
      }
      this.open = false
      // this.canClick = false
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        const data = JSON.parse(JSON.stringify(this.form))
        data.alarmUsers = addRes(data.alarmUsers)

        if (valid) {
          if (this.form.id != null) {
            updateServiceMonitor(data).then(response => {
              this.$dtModal.msgSuccess('修改成功')
              this.open = false
              this.canClick = true
              this.getList()
              this.$emit('getList')
              this.domains = [
                {
                  key_my: null,
                  value: null
                }
              ]
              this.interfaceAddress = ''
              this.interfaceType = ''
            })
          } else {
            addServiceMonitor(data).then(response => {
              this.$dtModal.msgSuccess('新增成功')
              this.open = false
              this.canClick = true
              this.$emit('getList')
              this.domains = [
                {
                  key_my: null,
                  value: null
                }
              ]
              this.interfaceAddress = ''
              this.interfaceType = ''
            })
          }
        }
      })
    },
    testConnect() {
      this.form.monitorParamList = JSON.parse(JSON.stringify(this.domains))
      const data = JSON.parse(JSON.stringify(this.form))
      data.alarmUsers = addRes(data.alarmUsers)
      this.$refs['form'].validate(valid => {
        if (valid) {
          connectTest(data).then(response => {
            if (response.data) {
              this.$dtModal.msgSuccess('连接成功')
              this.canClick = false
            } else {
              this.$dtModal.msgError('连接失败')
            }
          })
        }
      })
    },
    addCron() {
      this.$refs.vcrontabRef.showDialog()
    }
  }
}
</script>
